<template>
  <div class="setrole">
    <el-dialog :title="'为【'+roleinfo.name+'】分配权限'" :visible="showdialog" @close="cancel">
      <el-tree
        ref="mytree"
        :data="list"
        default-expand-all
        expand-on-click-node
        :check-strictly="true"
        show-checkbox
        :props="{label:'name'}"
        node-key="id"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getAllPerApi, setRoleassignApi } from '@/api/permission'
import { getRole } from '@/api/role'
export default {
  props: ['showdialog', 'roleinfo'],
  data() {
    return {
      // 树状结构数据源
      list: [],
      // 角色信息
      roledata: {}
    }
  },
  created() {
    this.getAllPer()
  },
  methods: {
    // 获取所有权限列表
    async getAllPer() {
      const res = await getAllPerApi()

      this.list = this.trunData(res, '0')
      console.log(this.list)
    },
    // 根据id获取角色对应权限
    async getPerById(id) {
      console.log(id)
      const res = await getRole(id)
      console.log(res)
      this.roledata = res
      this.$refs.mytree.setCheckedKeys(res.permIds)
      console.log(res)
    },
    // 转成树状结构
    trunData(arr, pid) {
      const newArr = []
      arr.forEach(item => {
        if (item.pid === pid) {
          item.children = this.trunData(arr, item.id)
          newArr.push(item)
        }
      })
      return newArr
    },
    // 根据角色id获得权限点
    cancel() {
      this.$emit('update:showdialog', false)
    },
    // 分配权限提交
    async submit() {
      try {
        const ids = this.$refs.mytree.getCheckedKeys()
        await setRoleassignApi({
          id: this.roledata.id,
          permIds: ids
        })
        this.$message.success('修改权限成功')
        this.$emit('update:showdialog', false)
      } catch {
        console.log('出错了')
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
